package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Component
public class OrderHandlerInterceptorContext implements ApplicationContextAware {

    // 定义一个List集合对象管理责任链接口的实现类对象
    private static final List<OrderHandlerInterceptor> ORDER_HANDLER_INTERCEPTORS = new ArrayList<>() ;

    /**
     * 责任链任务入口方法
     * @param orderInfoVo
     * @return
     */
    public static OrderInfoVo entry(OrderInfoVo orderInfoVo) {
        for(OrderHandlerInterceptor orderHandlerInterceptor : ORDER_HANDLER_INTERCEPTORS) {
            orderInfoVo = orderHandlerInterceptor.sbumitOrderRequestProcess(orderInfoVo) ;
        }
        return orderInfoVo ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Collection<OrderHandlerInterceptor> collection = applicationContext.getBeansOfType(OrderHandlerInterceptor.class).values();
        collection.stream().sorted((o1 , o2) -> o1.sort() - o2.sort()).forEach(orderHandlerInterceptor -> {
            ORDER_HANDLER_INTERCEPTORS.add(orderHandlerInterceptor) ;
        });
        log.info("责任链中所涉及到的任务对象已经被添加到list集合中...");
    }
}
